const express = require("express");
const bodyParser = require("body-parser");
var fs = require("fs");

const server = express();

server.listen(8080);

// 引入Multer
const multer = require("multer");

// 设置保存上传文件路径
const upload = multer({
  dest: "./static/upload",
});

// 处理上传文件
server.use(upload.any());

// 处理表单提交，对应请求头application/x-www-form-urlencoded
server.use(
  bodyParser.urlencoded({
    extended: false, // 为true时将使用qs库处理数据，通常不需要
  })
);

// 处理fetch请求，对应请求头application/json
server.use(bodyParser.json());

// 接收文件上传结果
server.post("/upload", (req, res, next) => {
  console.log(req.body);
  console.log(req.files);
  if (Array.isArray(req.files)) {
    for (let file of req.files) {
      fs.rename(
        file.path,
        "static/upload/" + file.originalname,
        function (err) {
          if (err) {
            throw err;
          }
        }
      );
    }
  }
  res.send({
    error: 0,
    data: req.body,
    msg: "上传成功",
  });
});

server.get("/reg", (req, res, next) => {
  console.log(req.query);
  res.send({
    error: 0,
    data: req.query,
    msg: "注册成功",
  });
});

server.post("/login", (req, res, next) => {
  console.log(req.body);
  res.send({
    error: 0,
    data: req.body,
    msg: "登陆成功",
  });
});

server.use(express.static("./static/"));

console.log(`Server started at http://localhost:8080/`);
